#include "libGeoutils/shape/Segment.h"
#include "nlohmann/json.hpp"
#include <sstream>

#define START_KEY "start"
#define END_KEY "end"

geo::shape::Segment::Segment()
{
	mStart = std::make_shared<Coord>();
	mEnd = std::make_shared<Coord>();
}

geo::shape::Segment::Segment(Coord::sptr start, Coord::sptr end)
	: mStart(start), mEnd(end)
{
}

geo::shape::Segment::~Segment()
{
}

void geo::shape::Segment::setStart(Coord::sptr start)
{
	mStart = start;
}

geo::shape::Coord::sptr geo::shape::Segment::getStart() const
{
	return mStart;
}

void geo::shape::Segment::setEnd(Coord::sptr end)
{
	mEnd = end;
}

geo::shape::Coord::sptr geo::shape::Segment::getEnd() const
{
	return mEnd;
}

bool geo::shape::Segment::to_string(std::string& out_str) const
{
	std::stringstream ss;
	Properties::to_string(out_str);
	ss << out_str;

	ss << "start coord: [";
	if (mStart) {
		ss << "(" << mStart->getLongitude() << ", " << mStart->getLatitude() << ")";
	} ss << "]";

	ss << "end coord: [";
	if (mEnd) {
		ss << "(" << mEnd->getLongitude() << ", " << mEnd->getLatitude() << ")";
	} ss << "]";

	out_str = ss.str();
	return true;
}

bool geo::shape::Segment::to_json(std::string& out_str) const
{
	nlohmann::json json;

	try
	{
		std::string op_str;

		if (mStart && mStart->to_json(op_str)) {
			nlohmann::json start_json_obj;
			start_json_obj = nlohmann::json::parse(op_str);
			json[START_KEY] = start_json_obj;
		}

		if (mEnd && mEnd->to_json(op_str)) {
			nlohmann::json end_json_obj;
			end_json_obj = nlohmann::json::parse(op_str);
			json[END_KEY] = end_json_obj;
		}

		out_str = json.dump();
		return true;
	}
	catch (const std::exception&)
	{
		mLastErrorMessage = "segment to_json exception!";
		return false;
	}
}

bool geo::shape::Segment::from_json(const std::string& in_str)
{
	return true;
}
